<?php
/**
 * Created by PhpStorm.
 * User: dongyanan
 * Date: 2019/7/4
 * Time: 4:58 PM
 */

namespace Ufile\Lumen\Ucloud;


class UcloudMUpload extends Ucloud
{
    public $uploadId;
    public $blkSize;

    public function __construct($bucket, $key, $file, $uploadId, $blkSize, $partNumber=0)
    {
        $this->bucket = $bucket;
        $this->path = $key;
        $this->file = $file;

        $this->key = $key;
        $this->uploadId = $uploadId;
        $this->blkSize = $blkSize;

        $this->setHost($bucket);
        $this->checkConfig(Ucloud::MUPLOAD);
        $this->getFileMimeType();

    }

    public function MUpload()
    {
        $blkSize = $this->blkSize;
        $partNumber = 0;

        $f = @fopen($this->file, "r");
        if (!$f) return array(null, new UcloudError(-1, -1, "open $this->file error"));

        for(;;) {

            if (@fseek($f, $blkSize*$partNumber, SEEK_SET) < 0) {
                fclose($f);
                return array(null, new UcloudError(0, -1, "fseek error"));
            }
            $content = @fread($f, $blkSize);
            if ($content == FALSE) {
                if (feof($f)) break;
                fclose($f);
                return array(null, new UcloudError(0, -1, "read file error"));
            }

            $this->setQuery($this->uploadId,$partNumber);
            $this->content = $content;

            $req = $this->getHttpRequestObj('PUT');

            $this->checkErr('UcloudMUpload');
            list($data, $err) = $this->clientCall($req);

            if ($err) {
                fclose($f);
                return array(null, $err);
            }
            $etag = @$data['ETag'];
            $part = @$data['PartNumber'];
            if ($part != $partNumber) {
                fclose($f);
                return array(null, new UcloudError(0, -1, "unmatch partnumber"));
            }
            $etagList[] = $etag;
            $partNumber += 1;
        }
        fclose($f);
        return array($etagList, null);
    }

    public function clientCall($req)
    {
        if ($this->errNo) {

            $http = new Http();

            list($resp, $err) = $http->UCloud_Client_Do($req);

            if ($err !== null) {
                return array(null, new UcloudError(0, -1, "m upload client do failed"));
            }

            list($data, $errClient) = $http->UCloud_Client_Ret($resp);

            if ($errClient !== null) {
                return array(null, new UcloudError(0, -1, "m upload client ret failed"));
            }

            return array($data, null);

        } else {

            return array(null, new UcloudError(0, -1, "something is wrong"));

        }
    }

    public function setQuery($uploadId,$partNumber=0)
    {
        $querys = array(
            "uploadId" => $uploadId,
            "partNumber" => $partNumber
        );

        $this->query = $querys;
    }
}